import api from "@/service/apiRequest"
import { UpdateUserInfo } from "@/types";
import Taro from "@tarojs/taro";

export const updateUserInfo = (payload) => {
    return {
        type: "UPDATE_USER_INFO",
        payload
    }
}

export async function asyncRequestUserInfo() {
    let authCode = await wechatLogin();
    // 异步请求
    let res = await api.post("/api/auth/register-login", {authCode});
    if (res && res.token) {
        Taro.setStorageSync("User-Token", res.token);
    }
    return updateUserInfo(res);
}

export async function asyncRequestUpdateUserInfo(params: UpdateUserInfo) {
    return async (dispatch, getState) => {
        // 异步请求
        const currentUserInfo = getState().userInfo;   
        let res = await api.post("/api/auth/user/update", params);
        if (res.result) {
            dispatch(updateUserInfo({...currentUserInfo, ...params}))
        }
    }
} 

async function wechatLogin() {
    return new Promise((resolve, reject) => {
        Taro.login({
            success: (res) => {
                resolve(res.code);
            },
            fail: (err) => {
                reject(err);
            }
        })
    })
}